const esbuild = await import('esbuild')

let result

let js = 'alert("test")'

result = esbuild.transformSync(js, {
    format: 'iife',
})

console.log(result)

// { warnings: [], code: '(() => {\n  alert("test");\n})();\n', map: '' }

// 0) 在源代码基础上套了一个 IIEF。

js = 'import React from "react"; export default { foo: "foo", React };'

result = esbuild.transformSync(js, {
    format: 'cjs',
})

/*

{
  warnings: [],
  code: 'var __create = Object.create;\n' +
    'var __defProp = Object.defineProperty;\n' +
    'var __getOwnPropDesc = Object.getOwnPropertyDescriptor;\n' +
    'var __getOwnPropNames = Object.getOwnPropertyNames;\n' +
    'var __getProtoOf = Object.getPrototypeOf;\n' +
    'var __hasOwnProp = Object.prototype.hasOwnProperty;\n' +
    'var __export = (target, all) => {\n' +
    '  for (var name in all)\n' +
    '    __defProp(target, name, { get: all[name], enumerable: true });\n' +
    '};\n' +
    'var __copyProps = (to, from, except, desc) => {\n' +
    '  if (from && typeof from === "object" || typeof from === "function") {\n' +
    '    for (let key of __getOwnPropNames(from))\n' +
    '      if (!__hasOwnProp.call(to, key) && key !== except)\n' +
    '        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n' +
    '  }\n' +
    '  return to;\n' +
    '};\n' +
    'var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n' +
    '  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,\n' +
    '  mod\n' +
    '));\n' +
    'var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);\n' +
    'var stdin_exports = {};\n' +
    '__export(stdin_exports, {\n' +
    '  default: () => stdin_default\n' +
    '});\n' +
    'module.exports = __toCommonJS(stdin_exports);\n' +
    'var import_react = __toESM(require("react"));\n' +
    'var stdin_default = { foo: "foo", React: import_react.default };\n',
  map: ''
}

 */

// 1) esm -> cjs 过程中，会引入两个 helper: __toESM & __toCommonJS
// __toESM 处理引入的 cjs 模块
// __toCommonJS 用于将当前模块处理成 cjs 模块

console.log(result)

result = esbuild.transformSync(js, {
    format: 'esm',
})

console.log(result)

/*
{
  warnings: [],
  code: 'import React from "react";\n' +
    'var stdin_default = { foo: "foo", React };\n' +
    'export {\n' +
    '  stdin_default as default\n' +
    '};\n',
  map: ''
}
*/

// 2） 会将 export default {} 处理成 var stdin_default = {}; export { stdin_default as default }

js = 'const React = require("react"); module.exports = { foo: "foo", React };'

result = esbuild.transformSync(js, {
    format: 'esm',
})

console.log(result)

// warnings: 'Converting "require" to "esm" is currently not supported'

// 3) cjs -> esm 还不支持
